<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class Dashboard extends Controller
{
    public function index(Request $request)
    {
        $res = [];
        $everydayWord = (new \App\Db\Dashboard())->getEverydayWord();
        if (!$everydayWord) {
            $everydayWord = $this->everydayWord($request);
            if ($everydayWord) {
                $everydayWord = json_decode($everydayWord, true);
                if ($everydayWord && $everydayWord['reason'] == 'success' && $everydayWord['result']['text']) {
                    (new \App\Db\Dashboard())->saveEverydayWord($everydayWord['result']['text']);
                    $res['everydayWord'] = $everydayWord['result']['text'];
                } else {
                    $res['everydayWord'] = '';
                }
            } else {
                $res['everydayWord'] = '';
            }
        } else {
            $res['everydayWord'] = $everydayWord->text;
        }

        $res['visitStatistic'] = (new \App\Db\Dashboard())->visitStatistic($request->siteId);
        $res['articleStatistic'] = (new \App\Db\Dashboard())->articleStatistic($request->siteId);

        return response()->json([
            'code' => 200,
            'msg' => '',
            'data' => $res
        ]);
    }

    public function everydayWord(Request $request)
    {
        $url = 'https://apis.juhe.cn/fapig/soup/query?key=' . env('EVERYDAY_WORD_JUHE_KEY');
        $juheRes = file_get_contents($url);
        return $juheRes;
    }
}
